import httpApi from '@/network/api'
import storage from '@/utils/storage.js'

const StorgeKey = {
	allCartList: 'cart_allCartList',
	checkCartIds: 'cart_checkCartIds',
}

// 购物车store
export default {
	state: {
		allCartList: storage.get(StorgeKey.allCartList, []), //购物车列表
		checkCartIds: storage.get(StorgeKey.checkCartIds, []), //选中的购物车id
	},
	mutations: {
		// 设置购物车列表
		SET_allCartList(state, list = []) {
			state.allCartList = list
			storage.set(StorgeKey.allCartList, list)
		},
		// 设置选中的购物车id
		SET_checkCartIds(state, ids) {
			state.checkCartIds = ids
			storage.set(StorgeKey.checkCartIds, ids)
		},
	},
	actions: {
		//获取购物车列表
		ac_getAllCartList({
			commit
		}, params) {
			return httpApi.api.get_shop_cartList(params).then((res) => {
				commit('SET_allCartList', res)
				return res
			})
		},
		// 购物车变更数量
		ac_editCartCount({
			commit,
			state
		}, {
			id,
			num
		}) {
			return httpApi.api.edit_shop_editCart({
				id,
				num
			}).then(() => {
				let newList = state.allCartList.map(v => {
					return v.id === id ? {
						...v,
						num
					} : {
						...v
					}
				})
				commit('SET_allCartList', newList)
				console.log(2222, newList);
			})
		},
		// 删除购物车商品
		ac_del_cartItems({
			dispatch,
			commit,
			state
		}, ids) {
			httpApi.api.del_shop_cartDel({
				ids: ids.toString()
			}).then(() => {
				commit('SET_allCartList', state.allCartList.filter(v => !ids.includes(v.id)))
				commit('SET_checkCartIds', [])
			})
		},
		// 加入购物车
		ac_add_cartItem({
			dispatch
		}, goodItem) {
			return httpApi.api.get_shop_addCart({
				goods_id: goodItem.id,
				num: 1
			}).then(res => {
				dispatch('ac_getAllCartList')
			})
		}
	},
	getters: {
		// 全部购物车条目
		allCartList: state => state.allCartList,
		// 购物车中所有商品数量总和
		allCartGoodsCount: state => state.allCartList?.reduce((p, v) => p + v.num, 0) || 0,
		// 选中的购物车id
		checkCartIds: state => state.checkCartIds,
		// 选中的购物车条目
		checkCartList: state => state.allCartList?.filter(v => state.checkCartIds?.includes(v.id)) || [],
		// 选中的总条数
		checkCardCount: (state, rootGetters) => rootGetters.checkCartList.reduce((p, v) => p + v.num, 0) || 0,
		// 选中的总金额
		checkCardPrice: (state, rootGetters) => rootGetters.checkCartList.reduce((p, v) => p + v.num * v.goods.price,
			0) || 0,
		// 是否全部选中
		checkCartAll: state => state.checkCartIds.length && state.allCartList.map(v => v.id).sort((a, b) => a - b)
			.toString() === state.checkCartIds.sort((a, b) => a - b).toString()
	}
}